package com.sc.es.service.user;

import com.sc.es.common.HouseResult;
import com.sc.es.dto.UserDto;
import com.sc.es.entity.Role;
import com.sc.es.entity.User;
import com.sc.es.repo.RoleRepository;
import com.sc.es.repo.UserRepository;
import com.sc.es.service.IUserService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sc
 * Created on  2018/2/6
 */
@Service
public class UserServiceImpl implements IUserService{

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private ModelMapper modelMapper;

    @Override
    public User findUserByName(String username) {
        User user = userRepository.findByName(username);
        if(user==null){
            return null;
        }
        List<Role> roles = roleRepository.findRolesByUserId(user.getId());
        if(roles.size()<1){
            throw new DisabledException("权限非法");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        roles.forEach(role->authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName())));
        user.setAuthorityList(authorities);
        return user;
    }

    @Override
    public HouseResult<UserDto> findById(Integer adminId) {
        User user = userRepository.findOne(adminId);
        if(user==null){
            return HouseResult.notFound();
        }
        return HouseResult.of(modelMapper.map(user,UserDto.class));
    }
}
